<template>
  <div class="home-container">
    <header class="header">
      <h1>咸阳北站自动化ETC系统</h1>
      <div class="header-actions">
        <!-- <a-button type="primary" @click="startAutomation" :loading="isRunning">
          启动自动化脚本
        </a-button> -->
        <a-button type="primary" @click="() => getAutoLoginCookie(false)"
          >自动化获取Cookie并更新</a-button
        >
        <!-- <a-button type="default" @click="openDevTools">开发者工具</a-button> -->
        <a-button type="default" @click="handleLogout">退出登录</a-button>
      </div>
    </header>
    <div class="content">
      <!-- Cookie设置面板 -->
      <a-card
        title="Cookie设置"
        class="cookie-card"
        style="margin-bottom: 20px"
      >
        <div class="cookie-input-area">
          <a-textarea
            v-model:value="cookieInput"
            placeholder="请输入或粘贴Cookie"
            :rows="3"
            :auto-size="{ minRows: 2, maxRows: 4 }"
          />
          <div class="cookie-actions" style="margin-top: 12px">
            <a-button type="primary" @click="handleManualCookieUpdate">
              更新Cookie
            </a-button>
            <span
              v-if="lastCookieUpdate"
              style="margin-left: 12px; color: #666"
            >
              上次更新: {{ lastCookieUpdate }}
            </span>
          </div>
        </div>
      </a-card>

      <!-- 添加定时提交部分 - 移动到这里 -->
      <a-card
        title="定时提交设置"
        class="auto-submit-card"
        style="margin-bottom: 20px"
      >
        <div class="auto-submit-content">
          <div class="form-group">
            <a-row :gutter="16" align="middle">
              <a-col :span="16">
                <a-space direction="vertical" style="width: 100%">
                  <span class="time-label">选择执行时间：</span>
                  <a-input
                    type="datetime-local"
                    v-model:value="scheduledTime"
                    placeholder="选择定时执行时间"
                    style="width: 100%"
                    :min="minDateTime"
                  />
                  <div class="tip-text">
                    系统会在定时任务执行前1分钟自动获取新Cookie，前5秒自动发起请求
                  </div>
                  <div v-if="countdownTime" class="countdown-text">
                    距离执行还有：{{ countdownTime }}
                  </div>
                </a-space>
              </a-col>
              <a-col :span="8" style="text-align: right">
                <a-button
                  type="primary"
                  @click="setAutoSubmit"
                  :disabled="!scheduledTime"
                  style="margin-right: 8px"
                >
                  设置定时任务
                </a-button>
                <a-button danger @click="cancelAutoSubmit"> 取消任务 </a-button>
              </a-col>
            </a-row>
          </div>

          <!-- 添加重试设置部分 -->
          <div
            class="retry-settings"
            style="
              margin-top: 20px;
              padding-top: 16px;
              border-top: 1px solid rgba(0, 0, 0, 0.05);
            "
          >
            <h4 style="margin-bottom: 16px; font-weight: 500">重试设置</h4>
            <a-row :gutter="16">
              <a-col :span="12">
                <div class="setting-item">
                  <span class="setting-label">最大重试次数：</span>
                  <a-input-number
                    v-model:value="maxRetryCount"
                    :min="1"
                    :max="1000"
                    style="width: 100%"
                    placeholder="设置最大重试次数"
                  />
                  <div class="setting-tip">
                    设置系统尝试创建工单的最大次数 (默认: 100)
                  </div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="setting-item">
                  <span class="setting-label">重试等待时间 (毫秒)：</span>
                  <a-input-number
                    v-model:value="retryWaitTime"
                    :min="100"
                    :max="10000"
                    :step="100"
                    style="width: 100%"
                    placeholder="设置重试间隔时间"
                  />
                  <div class="setting-tip">
                    设置每次重试之间的等待时间，单位为毫秒 (默认: 500)
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>

          <div
            v-if="autoSubmitStatus"
            :class="[
              'status-message',
              autoSubmitStatus.success ? 'success' : 'error',
            ]"
          >
            <div class="status-title">
              {{ autoSubmitStatus.success ? "定时任务状态" : "错误" }}
            </div>
            <div class="status-content">{{ autoSubmitStatus.message }}</div>
          </div>
        </div>
      </a-card>

      <!-- 工单创建面板 -->
      <a-card title="手工创建工单" class="work-order-card">
        <div class="import-panel">
          <div class="import-form">
            <h3>导入通行数据</h3>
            <div class="import-methods">
              <div class="method-card">
                <h4>方式一：本地文件导入</h4>
                <p class="method-desc">支持导入Excel文件(.xlsx)</p>
                <div class="upload-area">
                  <a-upload
                    accept=".xlsx,.xls"
                    :showUploadList="false"
                    :beforeUpload="handleExcelUpload"
                  >
                    <a-button type="primary">
                      <template #icon><upload-outlined /></template>
                      选择文件
                    </a-button>
                  </a-upload>
                  <span v-if="uploadFileName" class="file-name">{{
                    uploadFileName
                  }}</span>
                </div>
                <div class="excel-format-example">
                  <div class="example-header">
                    <h5>Excel格式示例：</h5>
                    <a-button type="link" size="small" @click="showImageExample"
                      >图片示例</a-button
                    >
                  </div>
                  <a-modal
                    v-model:visible="imageModalVisible"
                    title="Excel格式图片示例"
                    :footer="null"
                    width="800px"
                  >
                    <div class="example-image"></div>
                  </a-modal>
                  <table class="format-table">
                    <thead>
                      <tr>
                        <th class="first-row-header">
                          第一行必须"数据"俩字占位
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>01340110302302001803602020090108888 鲁A12345</td>
                      </tr>
                      <tr>
                        <td>01340110302302001803602020090108888 鲁A79810</td>
                      </tr>
                      <tr>
                        <td>01340110302302001803602020090108888 鲁A13245</td>
                      </tr>
                      <tr>
                        <td>01340110302302001803602020090108888 鲁A79810</td>
                      </tr>
                      <tr>
                        <td>01340110302302001803602020090108888 鲁A12345</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              <div class="method-card">
                <h4>方式二：文本粘贴导入</h4>
                <p class="method-desc">支持粘贴文本数据</p>
                <a-textarea
                  v-model:value="importData"
                  placeholder="导入格式为：通行标识+空格+车牌号码，如有多条通行，每条通行独占一行。"
                  :rows="8"
                  :auto-size="{ minRows: 6, maxRows: 10 }"
                ></a-textarea>
                <div class="example-text">
                  <p>例如：</p>
                  <p>01340110302302001803602020090108888 鲁A12345</p>
                  <p>01340110302302001803602020090108999 鲁A12345</p>
                </div>
                <a-button type="primary" @click="importTrafficData"
                  >导入文本数据</a-button
                >
              </div>
            </div>
          </div>

          <div class="traffic-data-preview" ref="tableContainer">
            <div class="preview-header">
              <div class="preview-header-left">
                <h3>通行数据预览</h3>
                <a-select
                  v-model:value="statusFilter"
                  style="width: 120px; margin-left: 16px"
                  @change="handleStatusChange"
                >
                  <a-select-option
                    v-for="option in statusOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </div>
              <div class="preview-header-right">
                <span class="data-count"
                  >共 {{ filteredData.length }} 条数据</span
                >
                <a-button
                  type="primary"
                  danger
                  @click="clearTrafficData"
                  :disabled="!trafficData.length"
                >
                  清空数据
                </a-button>
              </div>
            </div>
            <div class="table-wrapper" ref="tableContainer">
              <a-table
                :dataSource="filteredData"
                :columns="tableColumns"
                :pagination="{
                  total: filteredData.length,
                  current: currentPage,
                  pageSize: pageSize,
                  pageSizeOptions: ['50', '100', '200', '500'],
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                  position: ['bottomRight'],
                  size: 'default',
                  onChange: handlePageChange,
                  onShowSizeChange: handlePageSizeChange,
                }"
                :loading="tableLoading"
                size="small"
                :scroll="{ x: 1500 }"
                :locale="{
                  emptyText: '暂无数据',
                  filterConfirm: '确定',
                  filterReset: '重置',
                  filterEmptyText: '无筛选项',
                  selectAll: '全选当页',
                  selectInvert: '反选当页',
                  selectionAll: '全选所有',
                  sortTitle: '排序',
                  expand: '展开行',
                  collapse: '关闭行',
                  triggerDesc: '点击降序',
                  triggerAsc: '点击升序',
                  cancelSort: '取消排序',
                }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-tooltip
                      :title="Number(record.status) === 1 ? '' : '确认提交吗？'"
                      placement="top"
                    >
                      <a-button
                        :type="
                          Number(record.status) === 1 ? 'primary' : 'default'
                        "
                        size="small"
                        @click="toggleStatus(record)"
                        class="status-button"
                        :class="{
                          'status-pending': Number(record.status) !== 1,
                        }"
                      >
                        {{ Number(record.status) === 1 ? "已完成" : "待提交" }}
                      </a-button>
                    </a-tooltip>
                  </template>
                  <template v-else-if="column.key === 'operation'">
                    <a-button
                      type="link"
                      @click="deleteTrafficData(record.key)"
                      danger
                      >删除</a-button
                    >
                  </template>
                </template>
              </a-table>
            </div>

            <div class="actions-bar">
              <a-button type="primary" @click="createWorkOrder"
                >开始执行</a-button
              >
              <a-button @click="clearTrafficData">关闭</a-button>
            </div>
          </div>
        </div>
      </a-card>
    </div>
    <div
      class="back-to-top"
      :class="{ show: showBackToTop }"
      @click="handleBackToTop"
    >
      <a-button type="primary" shape="circle">
        <template #icon><up-outlined class="back-to-top-icon" /></template>
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  reactive,
  watch,
  nextTick,
  onUnmounted,
  h,
} from "vue";
import { useRouter } from "vue-router";
import { message, Modal } from "ant-design-vue";
import {
  UploadOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { SelectValue } from "ant-design-vue/es/select";
import { DefaultOptionType } from "ant-design-vue/es/select";
import type { TableColumnType } from "ant-design-vue";
import axios from "axios";
import dayjs from "dayjs";
// 导入所有数据文件
import ActualVehicleType from "./../data/ActualVehicleType.json";
import IssuingServiceOrganization from "./../data/IssuingServiceOrganization.json";
import LicencePlate from "./../data/LicencePlate.json";
import SuspectedEvasionType from "./../data/SuspectedEvasionType.json";
import VehicleModel from "./../data/VehicleModel.json";

const getActualVehicleTypeKey = (value: string) => {
  for (const [key, val] of Object.entries(ActualVehicleType)) {
    if (val === value) return key;
  }
  return "";
};

console.log("ActualVehicleType:", getActualVehicleTypeKey("紧急"));

const getIssuingServiceOrganizationKey = (value: string) => {
  for (const [key, val] of Object.entries(IssuingServiceOrganization)) {
    if (val === value) return key;
  }
  return "";
};

const getLicencePlateKey = (value: string) => {
  for (const [key, val] of Object.entries(LicencePlate)) {
    if (val === value) return key;
  }
  return "";
};

const getSuspectedEvasionTypeKey = (value: string) => {
  for (const [key, val] of Object.entries(SuspectedEvasionType)) {
    if (val === value) return key;
  }
  return "";
};

console.log("逃费类型", getSuspectedEvasionTypeKey);

const getVehicleModelKey = (value: string) => {
  for (const [key, val] of Object.entries(VehicleModel)) {
    if (val === value) return key;
  }
  return "";
};

// 扩展Window类型，添加应用所需的全局属性
declare global {
  interface Window {
    _automationResult: {
      success: boolean;
      message: string;
    } | null;
    // 修复primaryWindowAPI和electron的类型问题
    primaryWindowAPI: {
      submitTrafficData: (data: any[]) => Promise<any>;
      openDevTools: () => Promise<boolean>;
      readExcelFile: (filePath: string) => Promise<any>;
      runAutomation: () => Promise<any>;
      getCookie: (options: any) => Promise<any>;
      updateCookie: (cookieString: string) => Promise<any>;
      createWorkOrder: (data: any) => Promise<any>;
      autoLoginGetCookie: (options: any) => Promise<any>;
      setAutoSubmit: (scheduledTime: string) => Promise<any>;
      cancelAutoSubmit: () => Promise<any>;
      uploadImage: () => Promise<{
        success: boolean;
        attachCode?: string;
        message?: string;
      }>;
      uploadWordDocument: () => Promise<{
        success: boolean;
        fileName?: string;
        attachCode?: string;
        message?: string;
      }>;
    };
    electron: {
      ipcRenderer: {
        invoke: (channel: string, ...args: any[]) => Promise<any>;
        on: (
          channel: string,
          listener: (event: any, ...args: any[]) => void
        ) => void;
      };
      openDevTools: () => void;
    };
  }
}

interface StatusConfig {
  text: string;
  type: "default" | "primary" | "dashed" | "link" | "text";
  color: string;
}

// 状态配置
const STATUS_CONFIG: Record<string, StatusConfig> = {
  "0": {
    text: "待提交",
    type: "default",
    color: "#fa8c16",
  },
  "1": {
    text: "已完成",
    type: "primary",
    color: "#52c41a",
  },
};

// 状态选项
const statusOptions = [
  { label: "全部", value: "all" },
  { label: "待提交", value: 0 },
  { label: "已完成", value: 1 },
];

// 初始化全局变量
onMounted(() => {
  // 添加快捷键监听
  const pressedKeys = new Set();

  window.addEventListener("keydown", (event) => {
    // 将按键添加到集合中
    if (event.key === "Shift") pressedKeys.add("Shift");
    else if (event.key === "Control") pressedKeys.add("Control");
    else if (event.key === "Alt") pressedKeys.add("Alt");
    else pressedKeys.add(event.key.toLowerCase());

    // 检查是否所有需要的按键都被按下
    const requiredKeys = ["Shift", "Control", "Alt", "d", "e", "v"];
    const allKeysPressed = requiredKeys.every((key) => pressedKeys.has(key));

    if (allKeysPressed) {
      openDevTools();
      event.preventDefault();
    }
  });

  window.addEventListener("keyup", (event) => {
    // 从集合中移除释放的按键
    if (event.key === "Shift") pressedKeys.delete("Shift");
    else if (event.key === "Control") pressedKeys.delete("Control");
    else if (event.key === "Alt") pressedKeys.delete("Alt");
    else pressedKeys.delete(event.key.toLowerCase());
  });

  // 添加滚动监听
  window.addEventListener("scroll", handleScroll);

  // 自动执行获取Cookie
  getAutoLoginCookie(false);

  window._automationResult = null;

  // 添加数据变化监听
  watch(
    trafficData,
    (newVal) => {
      // console.log("trafficData 发生变化:", newVal);
    },
    { deep: true }
  );

  watch(filteredData, (newVal) => {
    // console.log("filteredData 发生变化:", newVal);
  });

  // 从localStorage获取已保存的Cookie
  const savedCookie = localStorage.getItem("etcCookie");
  if (savedCookie) {
    cookieInput.value = savedCookie;
    lastCookieUpdate.value = "从本地存储加载";
  }

  // 设置自动提交状态监听
  if (window.electron && window.electron.ipcRenderer) {
    window.electron.ipcRenderer.on(
      "auto-submit-status",
      (event: any, status: { success: boolean; message: string }) => {
        autoSubmitStatus.value = status;
        if (status.success) {
          message.success(status.message);
        } else {
          message.error(status.message);
        }
      }
    );

    // 监听触发自动登录事件
    window.electron.ipcRenderer.on("trigger-auto-login", async () => {
      console.log("收到定时任务触发的自动登录请求");
      await getAutoLoginCookie(true);
    });

    // 监听触发创建工单事件
    window.electron.ipcRenderer.on("trigger-create-work-order", async () => {
      console.log("收到定时任务触发的创建工单请求");
      await createWorkOrder();
    });
  }

  // 添加回到顶部相关的变量和函数
  const showBackToTop = ref(false);
});

const router = useRouter();
const isRunning = ref(false);
const progress = ref(0);
const statusMessage = ref("未启动");
const currentStep = ref(-1);
const activeTabKey = ref("1");
const pageSize = ref(100);

// 数据导入相关变量
const importData = ref("");
const trafficData = ref<any[]>([]);
const columns = ref<any[]>([]);
const statusFilter = ref("all");

// 获取状态配置
const getStatusConfig = (status: string): StatusConfig => {
  return STATUS_CONFIG[status] || STATUS_CONFIG["0"];
};

// 过滤后的数据
const filteredData = computed(() => {
  if (statusFilter.value === "all") {
    return trafficData.value;
  }
  const filterValue = Number(statusFilter.value);
  const filtered = trafficData.value.filter(
    (item: { status: number | string }) => Number(item.status) === filterValue
  );
  return filtered;
});

// 修改表格列配置，添加所有需要的字段
const tableColumns = computed(() => [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    width: 60,
    fixed: "left",
    align: "center",
  },
  {
    title: "通行标识",
    dataIndex: "trafficId",
    key: "trafficId",
    width: 200,
    ellipsis: true,
    align: "center",
  },
  {
    title: "车牌号",
    dataIndex: "plateNumber",
    key: "plateNumber",
    width: 100,
    align: "center",
  },
  {
    title: "逃费类型",
    dataIndex: "escapeType",
    key: "escapeType",
    width: 120,
    align: "center",
    customRender: ({ text }) => {
      return SuspectedEvasionType[text] || text;
    },
  },
  {
    title: "实际车牌",
    dataIndex: "actualPlate",
    key: "actualPlate",
    width: 100,
    align: "center",
  },
  {
    title: "车牌颜色",
    dataIndex: "plateColor",
    key: "plateColor",
    width: 100,
    align: "center",
    customRender: ({ text }) => {
      return LicencePlate[text] || text;
    },
  },
  {
    title: "车型",
    dataIndex: "vehicleType",
    key: "vehicleType",
    width: 100,
    align: "center",
    customRender: ({ text }) => {
      return VehicleModel[text] || text;
    },
  },
  {
    title: "车种",
    dataIndex: "vehicleClass",
    key: "vehicleClass",
    width: 100,
    align: "center",
    customRender: ({ text }) => {
      return ActualVehicleType[text] || text;
    },
  },
  {
    title: "车轴数",
    dataIndex: "axleCount",
    key: "axleCount",
    width: 80,
    align: "center",
  },
  {
    title: "发行机构",
    dataIndex: "issuerNo",
    key: "issuerNo",
    width: 120,
    align: "center",
    ellipsis: true,
    customRender: ({ text }) => {
      return IssuingServiceOrganization[text] || text;
    },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    width: 120,
    align: "center",
    ellipsis: true,
  },
  {
    title: "附件上传",
    key: "attachUpload",
    width: 120,
    align: "center",
    customRender: ({ record }) => {
      // 使用h函数替代JSX语法
      if (record.attachUploaded) {
        return h(
          "span",
          { style: { color: "#52c41a" } },
          record.attachCode || "已上传"
        );
      }
      return h(
        "a-button",
        {
          type: "primary",
          size: "small",
          onClick: () => uploadAttachment(record),
        },
        { default: () => "上传附件" }
      );
    },
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 80,
    align: "center",
    customRender: ({ text }) => {
      return text === 1 ? "已完成" : "待提交";
    },
    customCell: (record) => {
      return {
        class: `status-tag ${
          Number(record.status) === 1 ? "submitted" : "pending"
        }`,
      };
    },
  },
  {
    title: "发送信息",
    dataIndex: "sendInfo",
    key: "sendInfo",
    width: 120,
    ellipsis: true,
    align: "center",
  },
  {
    title: "描述",
    dataIndex: "description",
    key: "description",
    width: 120,
    ellipsis: true,
  },
  {
    title: "操作",
    key: "operation",
    width: 80,
    fixed: "right",
    align: "center",
    customRender: ({ record }) => {
      return h(
        "a-button",
        {
          type: "link",
          danger: true,
          onClick: () => deleteTrafficData(record.key),
        },
        { default: () => "删除" }
      );
    },
  },
]);

const uploadFileName = ref("");
const cookieInput = ref("");
const lastCookieUpdate = ref<string>("");

// 滚动到表格顶部的函数
const scrollToTableTop = () => {
  if (tableContainer.value) {
    const offset = 10; // 偏移量，可以根据实际情况调整
    const elementTop = tableContainer.value.getBoundingClientRect().top;
    const offsetPosition = elementTop + window.pageYOffset - offset;

    window.scrollTo({
      top: offsetPosition,
      behavior: "smooth",
    });
  }
};

// 处理页码改变
const handlePageChange = (page: number, pageSize: number) => {
  currentPage.value = page;
  scrollToTableTop();
};

// 处理每页条数改变
const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  scrollToTableTop();
};

// 处理状态变化
const handleStatusChange = (value: SelectValue) => {
  statusFilter.value = value as string;
  currentPage.value = 1;
  scrollToTableTop();
  const statusText =
    statusOptions.find((option) => option.value === value)?.label || "全部";
  message.success(`已切换到${statusText}状态`);
};

// 切换单条数据状态
const toggleStatus = (record: any) => {
  const index = trafficData.value.findIndex((item) => item.key === record.key);
  if (index !== -1) {
    const newData = JSON.parse(JSON.stringify(trafficData.value));
    newData[index].status = Number(newData[index].status) === 1 ? 0 : 1;
    const text = newData[index].status === 1 ? "已完成" : "待提交";
    trafficData.value = newData;
    message.success(`状态已更新为${text}`);
  }
};

// 导入通行数据
const currentPage = ref(1);
const tableLoading = ref(false);
const tableContainer = ref<HTMLElement | null>(null);

// 在导入数据时添加加载状态
const importTrafficData = async () => {
  if (!importData.value.trim()) {
    message.warning("请输入通行数据");
    return;
  }

  tableLoading.value = true;
  try {
    const lines = importData.value.trim().split("\n");
    const newData: any[] = [];

    lines.forEach((line, index) => {
      const parts = line.trim().split(/\s+/);
      if (parts.length >= 2) {
        // 至少需要通行标识和车牌号
        // 按照新的格式解析数据
        const trafficId = parts[0] || ""; // 通行标志
        const plateNumber = parts[1] || ""; // 车牌号码
        const escapeType = parts[2] || ""; // 疑似逃费类型
        const actualPlate = parts[3] || plateNumber; // 实际车牌
        const plateColor = parts[4] || "0"; // 实际车牌颜色
        const vehicleType = parts[5] || "1"; // 实际车型
        const vehicleClass = parts[6] || "0"; // 实际车种
        const axleCount = parts[7] || "2"; // 实际车轴
        const issuerNo = parts[8] || "110101"; // 发行服务机构
        const remark = parts[9] || ""; // 备注

        newData.push({
          key: trafficData.value.length + index + 1,
          trafficId,
          plateNumber,
          escapeType,
          actualPlate,
          plateColor,
          vehicleType,
          vehicleClass,
          axleCount,
          issuerNo,
          remark,
          status: 0,
          description: "",
          sendInfo: "",
          attachUploaded: false, // 添加附件上传状态
          attachFileName: "", // 添加附件文件名
        });
      }
    });

    if (newData.length > 0) {
      // 移除API调用代码，不再在导入时调用API
      const updatedData = [...trafficData.value, ...newData];
      trafficData.value = updatedData;
      message.success(`成功导入 ${newData.length} 条数据`);
      importData.value = ""; // 清空输入框
      currentPage.value = Math.ceil(updatedData.length / pageSize.value); // 跳转到最后一页
    }
  } catch (error) {
    message.error("导入数据时发生错误");
    console.error("导入数据错误:", error);
  } finally {
    tableLoading.value = false;
  }
};

// 修改Excel文件上传处理函数
const handleExcelUpload = async (file: File) => {
  tableLoading.value = true;
  try {
    // 检查文件类型
    const isExcel = /\.(xlsx|xls)$/i.test(file.name);
    if (!isExcel) {
      message.error("请选择Excel文件(.xlsx或.xls)");
      return false;
    }

    uploadFileName.value = file.name;

    // 获取文件路径
    const filePath = (file as any).path;
    if (!filePath) {
      throw new Error("无法获取文件路径");
    }

    // 读取Excel文件
    const result = await window.primaryWindowAPI.readExcelFile(filePath);
    console.log("Excel文件读取结果:", result);

    if (result.success && result.data) {
      console.log("Excel数据原始结构:", JSON.stringify(result.data, null, 2));
      console.log("Excel数据行数:", result.data.length);

      if (!Array.isArray(result.data) || result.data.length === 0) {
        message.warning("Excel文件中未找到数据，请检查文件内容");
        uploadFileName.value = "";
        return false;
      }

      // 使用更可靠的方法处理Excel数据
      const newData: any[] = [];

      // 特别标记第0行处理，从第0行开始，确保第一行不被跳过
      console.log("===== 开始处理Excel数据，从第0行开始 =====");

      for (let i = 0; i < result.data.length; i++) {
        const row = result.data[i];
        console.log(`===== 处理Excel第${i}行(0-indexed) =====`);
        console.log("当前行原始数据:", JSON.stringify(row));

        // 提取所有单元格的非空值
        const cellValues: string[] = [];
        for (const key in row) {
          const value = row[key];
          if (
            value !== null &&
            value !== undefined &&
            String(value).trim() !== ""
          ) {
            cellValues.push(String(value).trim());
            console.log(`- 单元格[${key}]=${String(value).trim()}`);
          }
        }

        console.log(`- 提取到的非空值:`, cellValues);

        if (cellValues.length === 0) {
          console.log(`- 第${i}行没有有效数据，跳过`);
          continue;
        }

        // 按照图片中的格式解析数据：通行标志 车牌号码 疑似逃费类型 实际车牌 实际车牌颜色 实际车型 实际车种 实际车轴 发行服务机构 备注
        if (cellValues.length >= 2) {
          const trafficId = cellValues[0] || ""; // 通行标志
          const plateNumber = cellValues[1] || ""; // 车牌号码
          const escapeType = cellValues.length > 2 ? cellValues[2] : "1002-8"; // 疑似逃费类型
          const actualPlate =
            cellValues.length > 3 ? cellValues[3] : plateNumber; // 实际车牌
          const plateColor = cellValues.length > 4 ? cellValues[4] : "0"; // 实际车牌颜色
          const vehicleType = cellValues.length > 5 ? cellValues[5] : "1"; // 实际车型
          const vehicleClass = cellValues.length > 6 ? cellValues[6] : "0"; // 实际车种
          const axleCount = cellValues.length > 7 ? cellValues[7] : "2"; // 实际车轴
          const issuerNo = cellValues.length > 8 ? cellValues[8] : "110101"; // 发行服务机构
          const remark = cellValues.length > 9 ? cellValues[9] : ""; // 备注

          newData.push({
            key: trafficData.value.length + newData.length + 1,
            trafficId,
            plateNumber,
            escapeType,
            actualPlate,
            plateColor,
            vehicleType,
            vehicleClass,
            axleCount,
            issuerNo,
            remark,
            status: 0,
            description: "",
            sendInfo: "",
            attachUploaded: false,
            attachFileName: "",
            attachCode: "",
          });
        }
      }

      console.log("Excel数据解析结果:", newData);

      if (newData.length > 0) {
        // 使用完全新的数组替换 trafficData.value
        const updatedData = [...trafficData.value, ...newData];
        trafficData.value = updatedData;
        message.success(`成功导入 ${newData.length} 条数据`);
        currentPage.value = Math.ceil(updatedData.length / pageSize.value); // 跳转到最后一页
      } else {
        message.warning("未能从Excel文件中提取有效数据");
      }
    } else {
      message.error(result.message || "读取Excel文件失败");
    }
  } catch (error: any) {
    console.error("Excel导入错误:", error);
    message.error(`Excel导入失败: ${error.message || "未知错误"}`);
  } finally {
    tableLoading.value = false;
    uploadFileName.value = "";
  }
  return false;
};

// 保留importSpecificData函数，但默认不使用
const importSpecificData = () => {
  // 注释保留，以便必要时可以使用
  const predefinedData = [
    {
      trafficId: "0199010032232180176712202503012211117",
      plateNumber: "辽MT0769",
    },
    {
      trafficId: "0137012304232367533606202503012223318",
      plateNumber: "鲁FDF512",
    },
    {
      trafficId: "0121012340230011071960202503010005438",
      plateNumber: "吉AZ2623",
    },
    {
      trafficId: "0121012340230011071960202503010005438",
      plateNumber: "吉AZ2624",
    },
    {
      trafficId: "0121012340230011071960202503010005438",
      plateNumber: "吉AZ2625",
    },
    {
      trafficId: "0121012340230011071960202503010005438",
      plateNumber: "吉AZ2626",
    },
    {
      trafficId: "0121012340230011071960202503010005438",
      plateNumber: "吉AZ2627",
    },
  ];

  const startIndex = trafficData.value.length + 1;
  const newData = predefinedData?.map((item, index) => ({
    key: startIndex + index,
    trafficId: item.trafficId,
    plateNumber: item.plateNumber,
    status: 0,
    description: "",
    sendInfo: "",
  }));

  // 将新数据添加到现有数据
  trafficData.value = [...trafficData.value, ...newData];
  message.success(`成功导入 ${newData.length} 条预设数据`);
};

// 删除通行数据
const deleteTrafficData = (key: number) => {
  trafficData.value = trafficData.value.filter((item) => item.key !== key);
  // 重新编号
  trafficData.value.forEach((item, index) => {
    item.key = index + 1;
  });
};

// 清空通行数据
const clearTrafficData = () => {
  if (trafficData.value.length === 0) {
    message.info("暂无数据可清空");
    return;
  }

  Modal.confirm({
    title: "确认清空",
    content: "确定要清空所有通行数据吗？此操作不可恢复。",
    okText: "确定清空",
    okType: "danger",
    cancelText: "取消",
    onOk() {
      trafficData.value = [];
      activeTabKey.value = "1";
      message.success("已清空所有数据");
    },
  });
};

// 创建工单
const createWorkOrder = async () => {
  const pendingData = trafficData.value.filter(
    (item: { status: number }) => Number(item.status) === 0
  );

  if (pendingData.length === 0) {
    message.warning("没有待提交的数据");
    return;
  }

  try {
    // 准备提交的数据
    const submitData = pendingData?.map((item) => ({
      passId: item.trafficId,
      vehiclePlate: item.plateNumber,
      origin: 5,
    }));

    // 打印要提交的数据
    console.log("要提交的数据:", JSON.stringify(submitData, null, 2));

    // 立即调用数据收集API - 将这个操作挪到最前面，放在Cookie检查之前
    try {
      message.loading({ content: "正在调用数据收集API...", key: "collectApi" });
      const response = await window.primaryWindowAPI.submitTrafficData(
        submitData
      );
      message.success({
        content: "数据收集API调用成功",
        key: "collectApi",
        duration: 2,
      });
      console.log("调用collect API响应:", response);
    } catch (apiError) {
      console.error("调用collect API失败:", apiError);
      message.error({
        content: "数据收集API调用失败",
        key: "collectApi",
        duration: 2,
      });
      // 即使API调用失败也继续后续流程
    }

    // 检查是否需要更新Cookie
    const savedCookie = localStorage.getItem("etcCookie");
    if (!savedCookie) {
      message.info("正在获取新的Cookie...");
      const newCookie = await getCookieValue();
      if (!newCookie) {
        message.error("无法获取Cookie，请重新登录");
        return;
      }
    }

    // 检查是否有状态为-1的数据
    const hasStatusNegativeOne = pendingData.some(
      (item) => Number(item.status) === -1
    );
    if (hasStatusNegativeOne) {
      // 更新所有待提交数据的状态为已完成
      const newData = JSON.parse(JSON.stringify(trafficData.value));
      newData.forEach(
        (item: { status: number; description: string; msg?: string }) => {
          if (Number(item.status) === -1) {
            item.description = item.msg || "工单已提交";
          }
        }
      );
      trafficData.value = newData;
      message.success(`成功更新 ${pendingData.length} 条数据状态`);
      return;
    }

    try {
      // 创建一个新的数据副本
      const newData = JSON.parse(JSON.stringify(trafficData.value));

      // 显示加载提示
      message.loading({
        content: `正在并行处理 ${submitData.length} 条数据，请稍候...`,
        duration: 0,
        key: "processLoading",
      });

      // 定义处理单条数据的函数
      const processItem = async (item: any, index: number) => {
        try {
          // 找到对应的数据索引
          const dataIndex = newData.findIndex(
            (dataItem: any) =>
              dataItem.trafficId === item.passId &&
              dataItem.plateNumber === item.vehiclePlate
          );

          if (dataIndex === -1) return;

          // 检查是否已上传附件
          if (!newData[dataIndex].attachUploaded) {
            message.warning(`第${index + 1}条数据未上传附件，请先上传`);
            newData[dataIndex].sendInfo = `请先上传附件`;
            trafficData.value = [...newData];
            return;
          }

          // 更新发送信息，标记为处理中
          newData[dataIndex].sendInfo = `处理中...`;
          // 实时更新表格数据
          trafficData.value = [...newData];

          // 使用已上传的附件的attachCode
          const attachCode = newData[dataIndex].attachCode;
          if (!attachCode) {
            throw new Error("未找到附件编码");
          }

          // 使用IPC通道发送请求
          let response;
          let retryCount = 0;
          let expectedResponse = false;
          const currentMaxRetries = maxRetryCount.value;
          const currentWaitTime = retryWaitTime.value;

          // 重试逻辑
          while (!expectedResponse && retryCount < currentMaxRetries) {
            response = await window.primaryWindowAPI.submitTrafficData([item]);
            console.log(`[${index}] 第${retryCount + 1}次请求响应:`, response);

            // 更新发送信息
            if (dataIndex !== -1) {
              newData[dataIndex].sendInfo = `重试次数: ${
                retryCount + 1
              }/${currentMaxRetries}`;
              // 实时更新表格数据
              trafficData.value = [...newData];
            }

            // 检查是否是预期的响应状态
            if (
              response &&
              response.success &&
              response.data &&
              (response.data.status === 0 || response.data.status === -1)
            ) {
              expectedResponse = true;
            } else {
              retryCount++;
              if (retryCount < currentMaxRetries) {
                await new Promise((resolve) =>
                  setTimeout(resolve, currentWaitTime)
                );
              }
            }

            // 检查响应中的status
            if (response.data.status === 0) {
              // 使用导入的数据构建工单
              const escapeType =
                getSuspectedEvasionTypeKey(newData[dataIndex].escapeType) ||
                "1002-8";
              const plateNumber = newData[dataIndex].plateNumber;
              const actualPlate = newData[dataIndex].actualPlate || plateNumber;
              const plateColor =
                getLicencePlateKey(newData[dataIndex].plateColor) || "0";
              //车型
              const vehicleType =
                getActualVehicleTypeKey(newData[dataIndex].vehicleType) || "1";
              //车种
              const vehicleClass =
                getVehicleModelKey(newData[dataIndex].vehicleClass) || "0";
              //车轴
              const axleCount = newData[dataIndex].axleCount || "2";
              //发行机构
              const issuerNo =
                getIssuingServiceOrganizationKey(newData[dataIndex].issuerNo) ||
                "110101";
              const remark = newData[dataIndex].remark || "";

              // 构建工单标题
              const escapeTypeText =
                SuspectedEvasionType[escapeType] || "其它改变缴费路径逃费";
              const vehicleColorText =
                getLicencePlateKey(LicencePlate[plateColor]) || "蓝色";
              const workOrderTitle = `${plateNumber}_${vehicleColorText}+${escapeTypeText}`;

              // 获取数据收集API返回的数据
              let collectApiData = null;
              if (
                response &&
                response.data &&
                response.data.data &&
                response.data.data.length > 0
              ) {
                collectApiData = response.data.data[0];
              }

              // 构建通行路径信息 - 使用数据收集API的数据
              const formattedData = collectApiData
                ? [collectApiData]
                : [
                    {
                      code: `${Math.floor(
                        Math.random() * 1000000000000
                      ).toString()}`,
                      passId: item.passId,
                      enStationInfo: {
                        stationNo: `G${Math.floor(
                          Math.random() * 10000000000
                        ).toString()}`,
                        stationName: "入口站",
                        passTime: dayjs()
                          .subtract(1, "day")
                          .format("YYYY-MM-DD HH:mm:ss"),
                        origin: null,
                      },
                      exStationInfo: {
                        stationNo: `G${Math.floor(
                          Math.random() * 10000000000
                        ).toString()}`,
                        stationName: "出口站",
                        passTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                        origin: null,
                      },
                      cardInfo: {
                        cardNo: Math.floor(
                          Math.random() * 10000000000000000000
                        ).toString(),
                        issuerNo: issuerNo,
                        provinceId: issuerNo.substring(0, 2),
                        provinceName: "省份",
                        origin: null,
                      },
                      obuInfo: {
                        cardNo: Math.floor(
                          Math.random() * 10000000000000000
                        ).toString(),
                        issuerNo: issuerNo,
                        provinceId: issuerNo.substring(0, 2),
                        provinceName: "省份",
                        origin: null,
                      },
                      mediaType: 1,
                      passSections: [
                        {
                          province: issuerNo.substring(0, 2),
                          provinceName: "省份",
                          sectionName: "高速路段",
                          sectionId: `G${Math.floor(
                            Math.random() * 1000000
                          ).toString()}`,
                          origin: null,
                        },
                      ],
                    },
                  ];

              // 获取cardInfo和obuInfo的数据 - 从数据收集API或使用默认值
              const cardNo =
                collectApiData && collectApiData.cardInfo
                  ? collectApiData.cardInfo.cardNo
                  : formattedData[0].cardInfo
                  ? formattedData[0].cardInfo.cardNo
                  : "";

              const obuCardNo =
                collectApiData && collectApiData.obuInfo
                  ? collectApiData.obuInfo.cardNo
                  : formattedData[0].obuInfo
                  ? formattedData[0].obuInfo.cardNo
                  : "";

              // 构建工单数据
              const workOrderData = {
                attachCode: attachCode, // 附件编码
                audits: formattedData.map((item) => ({
                  code: item.code,
                  passId: item.passId,
                  enStationInfo: item.enStationInfo,
                  exStationInfo: item.exStationInfo,
                  cardInfo: item.cardInfo,
                  obuInfo: item.obuInfo,
                  mediaType: item.mediaType,
                  passSections: item.passSections,
                })), // 数据收集API的数据
                title: workOrderTitle, // 车牌+车辆颜色+逃费类型拼接
                vehicleInfo: {
                  // 实际车辆信息，来自导入通行证
                  axleCount: axleCount.toString(),
                  vehicleClass: vehicleClass,
                  vehicleColor: plateColor,
                  vehicleId: `${actualPlate}_${plateColor}`,
                  vehiclePlate: actualPlate,
                  vehicleType: vehicleType,
                },
                escapeCodes: [escapeType], // 导入通行证提供
                issuerProcess: true, // 固定为true
                offlinePay: false, // 固定为false
                offlinePayDTOInfo: {
                  payType: 1,
                  payWay: 2,
                }, // 固定值
                origin: 5, // 固定值
                type: 0, // 固定值
                cardInfos: [
                  // 卡信息，组合数据
                  {
                    cardNo: cardNo, // 从数据收集API获取
                    issuerNo: issuerNo, // 从导入通行证获取
                  },
                ],
                obuInfos: [
                  // OBU信息，组合数据
                  {
                    cardNo: obuCardNo, // 从数据收集API获取
                    issuerNo: issuerNo, // 从导入通行证获取
                  },
                ],
                remark: remark || "备注信息", // 从导入通行证获取
              };

              // 打印详细的工单数据
              console.log(
                `[${index}] 工单提交数据:`,
                JSON.stringify(workOrderData, null, 2)
              );

              // 发送工单创建请求
              const createOrderResponse =
                await window.primaryWindowAPI.createWorkOrder(workOrderData);
              console.log(`[${index}] 工单创建响应:`, createOrderResponse);

              if (createOrderResponse.success) {
                // 更新当前处理的这条数据的状态
                if (dataIndex !== -1) {
                  newData[dataIndex].status = 1;
                  newData[dataIndex].description =
                    createOrderResponse.data?.msg || "工单创建成功";
                  newData[dataIndex].sendInfo = `成功(重试${retryCount}次)`;
                  // 实时更新表格数据
                  trafficData.value = [...newData];
                }
              }
            } else if (response.data.status === -1) {
              // status为-1时，标记当前数据为已处理
              if (dataIndex !== -1) {
                newData[dataIndex].status = 1;
                newData[dataIndex].description =
                  response.data.msg || "已标记为完成";
                newData[dataIndex].sendInfo = `已完成(${
                  response.data.msg || ""
                })`;
                // 实时更新表格数据
                trafficData.value = [...newData];
              }
            }
          }

          // 如果所有重试都失败
          if (!expectedResponse) {
            if (dataIndex !== -1) {
              newData[dataIndex].sendInfo = `请求失败，已达到最大重试次数`;
              // 实时更新表格数据
              trafficData.value = [...newData];
            }
          }
        } catch (error: any) {
          console.error(`处理数据失败:`, error);
          message.error(`处理数据失败: ${error.message || "未知错误"}`);
        }
      };

      // 创建并发处理任务
      const tasks = submitData.map((item, index) => processItem(item, index));

      // 等待所有任务完成
      await Promise.all(tasks);

      // 隐藏加载提示
      message.success(`所有任务处理完成`, 3);
      message.destroy("processLoading");
    } catch (error: any) {
      console.error("批量处理失败:", error);
      message.error(`批量处理失败: ${error.message || "未知错误"}`);
      message.destroy("processLoading");
    }
  } catch (error: any) {
    console.error("处理错误:", error);
    message.error(`操作失败: ${error.message || "未知错误"}`);
  }
};

// 定义自动化步骤
const automationSteps = [
  "初始化自动化环境",
  "读取配置信息",
  "连接到ETC系统",
  "执行交易处理",
  "生成交易报告",
  "完成自动化流程",
];

// 进度条状态
const progressStatus = computed(() => {
  if (progress.value === 100) return "success";
  return "active";
});

// 修改模拟进度函数，在完成时处理自动化结果
const simulateProgress = (step: number) => {
  currentStep.value = step;

  // 每个步骤对应的进度区间
  const stepProgress = Math.floor(100 / automationSteps.length);
  const startProgress = step * stepProgress;
  const endProgress = (step + 1) * stepProgress;

  // 从当前步骤的起始进度开始递增
  progress.value = startProgress;

  const interval = setInterval(() => {
    progress.value += 1;

    // 达到当前步骤的最大进度时停止
    if (progress.value >= endProgress) {
      clearInterval(interval);

      // 如果还有下一步，继续模拟下一步进度
      if (step < automationSteps.length - 1) {
        setTimeout(() => {
          simulateProgress(step + 1);
        }, 500);
      } else {
        // 所有步骤完成，进度条达到100%
        progress.value = 100;

        // 延迟一会儿再显示完成消息，让用户能看到100%的进度
        setTimeout(() => {
          isRunning.value = false;

          // 根据实际的执行结果更新UI
          if (window._automationResult) {
            const result = window._automationResult;

            if (result.success) {
              message.success(result.message);
              statusMessage.value = `自动化成功: ${result.message}`;
            } else {
              message.error(result.message);
              statusMessage.value = `自动化失败: ${result.message}`;
            }

            // 清除结果，避免内存泄漏
            window._automationResult = null;
          } else {
            statusMessage.value = "自动化流程已完成";
            message.success("自动化流程已完成");
          }
        }, 1000);
      }
    }
  }, 100);
};

// 重写startAutomation函数，协调自动化执行和进度显示
const startAutomation = async () => {
  if (isRunning.value) return;

  isRunning.value = true;
  progress.value = 0;
  currentStep.value = -1;
  statusMessage.value = "自动化流程启动中...";

  // 清除任何之前的结果
  window._automationResult = null;

  try {
    // 调用主进程的自动化API，但不等待结果
    window.primaryWindowAPI
      .runAutomation()
      .then((result) => {
        // 存储结果，但不立即显示
        window._automationResult = result;
      })
      .catch((error) => {
        console.error("自动化执行失败:", error);
        window._automationResult = {
          success: false,
          message: error.message || "未知错误",
        };
      });

    // 开始进度条动画，不等待API执行完成
    setTimeout(() => {
      simulateProgress(0);
    }, 500);
  } catch (error: any) {
    console.error("启动自动化过程失败:", error);
    message.error("启动失败: " + (error.message || "未知错误"));
    isRunning.value = false;
    statusMessage.value = "启动失败";
  }
};

const getCookieValue = async () => {
  try {
    message.info("正在获取Cookie...");

    // 从首页获取Cookie
    const response = await axios.get(
      "http://bsdts.chinaetc.org/ass/index/home",
      {
        maxRedirects: 5,
        validateStatus: (status) => status < 400,
        withCredentials: true,
        headers: {
          Accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
          "Accept-Language": "zh-CN,zh;q=0.9",
          "Cache-Control": "no-cache",
          Connection: "keep-alive",
          Pragma: "no-cache",
          "Upgrade-Insecure-Requests": "1",
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        },
      }
    );

    // console.log('首页响应状态:', response.status);
    // console.log('首页响应头:', response.headers);

    // 从响应头中获取Cookie
    const cookies = response.headers["set-cookie"];
    if (cookies) {
      let cookieString = "";
      if (Array.isArray(cookies)) {
        cookies.forEach((cookie) => {
          const [mainPart] = cookie.split(";");
          cookieString += mainPart + "; ";
        });
      } else {
        cookieString = cookies;
      }

      cookieString = cookieString.trim();
      // console.log('解析到的Cookie:', cookieString);

      // 将新的Cookie保存到localStorage中
      localStorage.setItem("etcCookie", cookieString);

      // 通知主进程更新Cookie
      const updateResult = await window.primaryWindowAPI.updateCookie(
        cookieString
      );
      // console.log('更新Cookie结果:', updateResult);

      if (updateResult.success) {
        message.success("Cookie已更新");
        return cookieString;
      } else {
        throw new Error(updateResult.message || "更新Cookie失败");
      }
    }

    // 如果没有在set-cookie中找到，尝试其他方式
    const allHeaders = response.headers;
    // console.log('所有响应头:', allHeaders);

    if (allHeaders.cookie || allHeaders.Cookie) {
      const cookieString = (allHeaders.cookie || allHeaders.Cookie).toString();
      // console.log('从headers中获取到的Cookie:', cookieString);

      localStorage.setItem("etcCookie", cookieString);
      const updateResult = await window.primaryWindowAPI.updateCookie(
        cookieString
      );

      if (updateResult.success) {
        message.success("Cookie已更新");
        return cookieString;
      } else {
        throw new Error(updateResult.message || "更新Cookie失败");
      }
    }

    throw new Error("未能从响应中获取到Cookie");
  } catch (error: any) {
    console.error("获取Cookie失败:", error);
    console.error("错误详情:", {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
    });
    message.error("获取Cookie失败: " + (error.message || "未知错误"));
    return null;
  }
};

const handleLogout = () => {
  localStorage.removeItem("token");
  localStorage.clear();
  router.push("/login");
};

const openDevTools = () => {
  // 使用专门的openDevTools方法
  if (window.primaryWindowAPI) {
    // @ts-ignore - openDevTools方法已在preload中定义
    window.primaryWindowAPI
      .openDevTools()
      .then((result: boolean) => {
        // console.log('开发者工具调用结果:', result);
        if (!result) {
          message.warning("开发者工具可能未能成功打开");
        }
      })
      .catch((err: Error) => {
        console.error("打开开发者工具失败:", err);
        message.error("无法打开开发者工具");
      });
  } else {
    console.error("openDevTools方法不存在");
    message.error("无法打开开发者工具，API不可用");
  }
};

// 处理手动更新Cookie
const handleManualCookieUpdate = async () => {
  if (!cookieInput.value.trim()) {
    message.warning("请输入Cookie");
    return;
  }

  try {
    // 保存到localStorage
    localStorage.setItem("etcCookie", cookieInput.value.trim());

    // 通知主进程更新Cookie
    const updateResult = await window.primaryWindowAPI.updateCookie(
      cookieInput.value.trim()
    );

    if (updateResult.success) {
      lastCookieUpdate.value = new Date().toLocaleString();
      message.success("Cookie已更新");
    } else {
      throw new Error(updateResult.message || "更新Cookie失败");
    }
  } catch (error: any) {
    console.error("更新Cookie失败:", error);
    message.error("更新Cookie失败: " + (error.message || "未知错误"));
  }
};

// 自动登录并获取Cookie
const getAutoLoginCookie = async (isScheduledTask: boolean = false) => {
  try {
    const loadingKey = "cookieLoading";
    message.loading({
      content: isScheduledTask
        ? "定时任务即将执行，正在刷新Cookie..."
        : "正在获取Cookie...",
      key: loadingKey,
      duration: 0,
    });

    const result = await window.primaryWindowAPI.autoLoginGetCookie({
      loginUrl:
        "http://bsdts.chinaetc.org/sso/app/oauth/login?client_id=000061&response_type=code&redirect_uri=http://bsdts.chinaetc.org/ass/login/common/oauth&scope=USERINFO&state=state",
      username: localStorage.getItem("username"),
      password: localStorage.getItem("password"),
    });

    message.destroy(loadingKey);

    if (result.success && result.cookie) {
      cookieInput.value = result.cookie;
      localStorage.setItem("etcCookie", result.cookie);
      await window.primaryWindowAPI.updateCookie(result.cookie);
      message.success({
        content: isScheduledTask ? "定时任务Cookie已更新" : "获取Cookie成功",
        duration: 3,
      });
    } else {
      message.error(result.message || "获取Cookie失败，请稍后重试");
    }
  } catch (error) {
    message.destroy("cookieLoading");
    message.error("获取Cookie失败，请稍后重试");
    console.error("获取Cookie出错:", error);
  }
};

// 定时提交相关
const scheduledTime = ref("");
const autoSubmitStatus = ref<{ success: boolean; message: string } | null>(
  null
);
const maxRetryCount = ref(100); // 默认最大重试次数为100
const retryWaitTime = ref(500); // 默认重试等待时间为500毫秒

// 计算最小可选择时间（当前时间）
const minDateTime = computed(() => {
  const now = new Date();
  return now.toISOString().slice(0, 16); // 格式为 YYYY-MM-DDTHH:mm
});

// 设置定时提交
const setAutoSubmit = async () => {
  if (!scheduledTime.value) {
    message.warning("请选择定时执行时间");
    return;
  }

  // 检查是否有导入的数据
  if (!trafficData.value || trafficData.value.length === 0) {
    message.warning("请先导入数据后再设置定时任务");
    return;
  }

  // 检查是否有待提交的数据
  const pendingData = trafficData.value.filter(
    (item: { status: number }) => Number(item.status) === 0
  );

  if (pendingData.length === 0) {
    message.warning("没有待提交的数据，请确保有需要处理的数据后再设置定时任务");
    return;
  }

  try {
    const result = await window.primaryWindowAPI.setAutoSubmit(
      scheduledTime.value
    );
    autoSubmitStatus.value = result;
    if (result.success) {
      message.success(result.message);
    } else {
      message.error(result.message);
    }
  } catch (error) {
    message.error("设置定时任务失败");
    console.error("设置定时任务失败:", error);
  }
};

// 在 script setup 部分添加倒计时相关的代码
const countdownTime = ref("");
let countdownInterval: ReturnType<typeof setInterval> | null = null;

// 更新倒计时显示
const updateCountdown = () => {
  if (!scheduledTime.value) {
    countdownTime.value = "";
    return;
  }

  const now = new Date().getTime();
  const targetTime = new Date(scheduledTime.value).getTime();
  const timeDiff = targetTime - now;

  if (timeDiff <= 0) {
    countdownTime.value = "时间已到";
    if (countdownInterval) {
      clearInterval(countdownInterval);
      countdownInterval = null;
    }
    return;
  }

  const hours = Math.floor(timeDiff / (1000 * 60 * 60));
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

  countdownTime.value = `${hours}小时 ${minutes}分钟 ${seconds}秒`;

  // 在定时前1分钟自动获取cookie
  if (hours === 0 && minutes === 1 && seconds === 0) {
    console.log("定时任务将在1分钟后执行，开始自动获取Cookie...");
    getAutoLoginCookie(true);
  }

  // 在定时前5秒发起请求
  if (hours === 0 && minutes === 0 && seconds === 5) {
    console.log("定时任务将在5秒后执行，开始发起请求...");
    createWorkOrder();
  }
};

// 监听scheduledTime的变化
watch(scheduledTime, (newValue) => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
    countdownInterval = null;
  }

  if (newValue) {
    updateCountdown();
    countdownInterval = setInterval(updateCountdown, 1000);
  } else {
    countdownTime.value = "";
  }
});

// 组件卸载时清理定时器
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
  if (countdownInterval) {
    clearInterval(countdownInterval);
    countdownInterval = null;
  }
});

// 取消定时提交
const cancelAutoSubmit = async () => {
  try {
    const result = await window.primaryWindowAPI.cancelAutoSubmit();
    autoSubmitStatus.value = result;
    if (result.success) {
      message.success(result.message);
      scheduledTime.value = "";
      // 清除倒计时
      if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
      }
      countdownTime.value = "";
    } else {
      message.error(result.message);
    }
  } catch (error) {
    message.error("取消定时任务失败");
    console.error("取消定时任务失败:", error);
  }
};

// 在 script setup 中添加
const imageModalVisible = ref(false);

const showImageExample = () => {
  imageModalVisible.value = true;
};

// 添加回到顶部相关的变量和函数
const showBackToTop = ref(false);

// 监听滚动事件
const handleScroll = () => {
  if (tableContainer.value) {
    const tableTop = tableContainer.value.getBoundingClientRect().top;
    showBackToTop.value = tableTop < 0;
  }
};

const handleBackToTop = () => {
  if (tableContainer.value) {
    const tableTop = tableContainer.value.offsetTop - 20;
    window.scrollTo({
      top: tableTop,
      behavior: "smooth",
    });
  }
};

// 修改上传附件函数
const uploadAttachment = async (record: any) => {
  try {
    // 使用现有的上传图片功能
    const result = await window.primaryWindowAPI.uploadImage();

    if (result.success && result.attachCode) {
      // 构建新的attachCode：固定前缀 + 随机10位数
      const prefix = "20240730164031371820874701845886174"; // 固定的35位前缀
      const randomSuffix = Math.floor(Math.random() * 10000000000)
        .toString()
        .padStart(10, "0");
      const modifiedAttachCode = prefix + randomSuffix;

      console.log(`原始attachCode: ${result.attachCode}`);
      console.log(`修改后attachCode: ${modifiedAttachCode}`);
      console.log(`attachCode长度: ${modifiedAttachCode.length}`);

      // 更新记录
      const index = trafficData.value.findIndex(
        (item) => item.key === record.key
      );
      if (index !== -1) {
        trafficData.value[index].attachUploaded = true;
        trafficData.value[index].attachFileName = "已上传附件";
        trafficData.value[index].attachCode = modifiedAttachCode;
        message.success(`附件上传成功，附件编码: ${modifiedAttachCode}`);
      }
    } else {
      message.error(result.message || "上传失败");
    }
  } catch (error: any) {
    console.error("上传附件失败:", error);
    message.error(`上传附件失败: ${error.message || "未知错误"}`);
  }
};
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f5f7;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text",
    "Helvetica Neue", Arial, sans-serif;
}

.header {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 0 rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header h1 {
  margin: 0;
  color: #1d1d1f;
  font-size: 20px;
  font-weight: 500;
  letter-spacing: -0.02em;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.work-order-card,
.cookie-card,
.auto-submit-card {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: none;
  margin-bottom: 24px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.work-order-card:hover,
.cookie-card:hover,
.auto-submit-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 12px rgba(0, 0, 0, 0.08);
}

.import-form {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.import-form h3 {
  margin-top: 0;
  color: #1d1d1f;
  margin-bottom: 20px;
  font-weight: 500;
}

.method-card {
  background-color: rgba(255, 255, 252, 0.9);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  padding: 24px;
  border: 1px solid rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.method-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.method-card h4 {
  margin: 0 0 12px 0;
  color: #1d1d1f;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: -0.01em;
}

.method-desc {
  color: #86868b;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.upload-area {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-name {
  color: #86868b;
  font-size: 14px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 12px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.preview-header-left {
  display: flex;
  align-items: center;
}

.preview-header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.data-count {
  color: #86868b;
  font-size: 14px;
}

.status-tag {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 13px;
  line-height: 1.4;
  font-weight: 500;
}

.status-tag.pending {
  background-color: rgba(255, 149, 0, 0.1);
  color: #ff9500;
  border: 1px solid rgba(255, 149, 0, 0.2);
}

.status-tag.submitted {
  background-color: rgba(52, 199, 89, 0.1);
  color: #34c759;
  border: 1px solid rgba(52, 199, 89, 0.2);
}

.actions-bar {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

/* 按钮样式优化 */
:deep(.ant-btn) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #0071e3, #0077ed);
  border: none;
  box-shadow: 0 2px 4px rgba(0, 113, 227, 0.2);
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(135deg, #0077ed, #0071e3);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 113, 227, 0.3);
}

:deep(.ant-btn-default) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.ant-btn-default:hover) {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式优化 */
:deep(.ant-table) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 16px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  font-weight: 500;
  color: #1d1d1f;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(0, 0, 0, 0.02);
}

/* 输入框样式优化 */
:deep(.ant-input),
:deep(.ant-input-textarea) {
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.ant-input:hover),
:deep(.ant-input-textarea:hover) {
  border-color: #0071e3;
}

:deep(.ant-input:focus),
:deep(.ant-input-textarea:focus) {
  border-color: #0071e3;
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.2);
}

/* 倒计时样式优化 */
.countdown-text {
  color: #0071e3;
  font-size: 14px;
  font-weight: 500;
  margin-top: 12px;
  padding: 12px 16px;
  background-color: rgba(0, 113, 227, 0.1);
  border-radius: 12px;
  display: inline-block;
  border: 1px solid rgba(0, 113, 227, 0.2);
}

/* 回到顶部按钮样式优化 */
.back-to-top {
  position: fixed;
  right: 40px;
  bottom: 40px;
  cursor: pointer;
  z-index: 999;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  opacity: 0;
  transform: translateY(20px);
  pointer-events: none;
}

.back-to-top.show {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}

.back-to-top button {
  width: 48px;
  height: 48px;
  font-size: 20px;
  background: linear-gradient(135deg, #0071e3, #0077ed);
  border: none;
  box-shadow: 0 4px 12px rgba(0, 113, 227, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.back-to-top button:hover {
  transform: translateY(-3px) scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 113, 227, 0.4);
  background: linear-gradient(135deg, #0077ed, #0071e3);
}

/* 消息提示样式优化 */
:deep(.ant-message) {
  top: 24px;
}

:deep(.ant-message-notice) {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

:deep(.ant-message-success) {
  background: rgba(52, 199, 89, 0.1);
  border: 1px solid rgba(52, 199, 89, 0.2);
}

:deep(.ant-message-error) {
  background: rgba(255, 59, 48, 0.1);
  border: 1px solid rgba(255, 59, 48, 0.2);
}

:deep(.ant-message-info) {
  background: rgba(0, 113, 227, 0.1);
  border: 1px solid rgba(0, 113, 227, 0.2);
}

/* 模态框样式优化 */
:deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px 24px;
}

:deep(.ant-modal-title) {
  font-weight: 500;
  color: #1d1d1f;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-modal-footer) {
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  padding: 16px 24px;
}

/* 选择器样式优化 */
:deep(.ant-select) {
  border-radius: 8px;
}

:deep(.ant-select-selector) {
  border-radius: 8px !important;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: #0071e3 !important;
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.2) !important;
}

/* 分页器样式优化 */
:deep(.ant-pagination) {
  margin-top: 24px;
}

:deep(.ant-pagination-item) {
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.ant-pagination-item-active) {
  background: #0071e3;
  border-color: #0071e3;
}

:deep(.ant-pagination-item:hover) {
  border-color: #0071e3;
}

:deep(.ant-pagination-prev .ant-pagination-item-link),
:deep(.ant-pagination-next .ant-pagination-item-link) {
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.import-methods {
  display: flex;
  flex-direction: row;
  gap: 20px;
  margin-bottom: 20px;
}

.method-card {
  flex: 1;
  background-color: rgba(250, 250, 252, 0.9);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  padding: 24px;
  border: 1px solid rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.method-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.method-card h4 {
  margin: 0 0 12px 0;
  color: #1d1d1f;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: -0.01em;
}

.method-desc {
  color: #86868b;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.example-text {
  margin: 16px 0;
  color: #86868b;
  font-size: 14px;
  background-color: rgba(0, 0, 0, 0.02);
  padding: 12px;
  border-radius: 8px;
  flex-grow: 1;
}

/* 确保文本区域在方式二中有足够的高度 */
:deep(.ant-input-textarea) {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

:deep(.ant-input-textarea .ant-input) {
  flex-grow: 1;
  min-height: 120px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .import-methods {
    flex-direction: column;
  }
}

.retry-settings {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  padding: 16px;
  margin-top: 20px;
}

.setting-item {
  margin-bottom: 12px;
}

.setting-label {
  display: block;
  margin-bottom: 8px;
  color: #1d1d1f;
  font-weight: 500;
  font-size: 14px;
}

.setting-tip {
  margin-top: 6px;
  color: #86868b;
  font-size: 12px;
  line-height: 1.4;
}

:deep(.ant-input-number) {
  width: 100%;
  border-radius: 8px;
}

:deep(.ant-input-number:hover) {
  border-color: #0071e3;
}

:deep(.ant-input-number-focused) {
  border-color: #0071e3;
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.2);
}
</style>
